package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.IOException;

import static org.springframework.amqp.rabbit.annotation.Exchange.TRUE;

/**
 * Package: com.atguigu.tingshu.account.receiver
 *
 * @author xiongkunYang
 * @description:
 * @since 2025/6/16 14:43
 */
@Slf4j
@Component
public class AccountReceiver {

    private final UserAccountService accountService;

    public AccountReceiver(UserAccountService accountService) {
        this.accountService = accountService;
    }

    /**
     * 监听用户注册成功消息, 初始化账户（余额）记录
     *
     * @param userId  用户id
     * @param message 消息
     * @param channel 信道
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_USER),
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER, durable = TRUE),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void userRegister(Long userId, Message message, Channel channel) {
        Assert.notNull(userId, "用户id不能为空");
        log.info("[账户服务]监听用户注册成功消息，用户id：{}", userId);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            this.accountService.saveUserAccount(userId);
            channel.basicAck(deliveryTag, false);
            log.info("[账户服务]用户id：{}, 初始化账户（余额）记录成功", userId);
        } catch (IOException e) {
            log.error("[账户服务]用户id：{}, 初始化账户（余额）记录失败", userId);
            channel.basicNack(deliveryTag, false, true);
        }
    }
}